<template>
  <div>
    <div class="video-container">
      <!-- 后退导航 -->
      <div v-show="smallWindow && goBackShow" class="back-top">
        <div class="goBack icon-back" @click.stop="goBack"></div>
      </div>

      <div class="video-play">
        <hxmH5Video v-if="!lowVersion" :config="config" @player="getPlayerInstance" />
        <div v-else class="lowVersion" @click="playVideo(config.url)">
          <img alt="" :src="config.poster" />
        </div>
      </div>
      <div class="pay-tip card-bg-red" v-if="!auth && !adblockNormal">
        <div class="pay-tip-left">
          <div class="fs-28 lh-34 bold">本课程是付费专享内容</div>
          <div class="fs-24 lh-30 cl-r mt-4">试看中…</div>
        </div>
        <div class="pay-tip-btn bg-r" @click.stop="goInfo('ffxx')">付费学习</div>
      </div>
      <div class="adbolck" v-show="adblockNormal">
        <div class="buy-tip">课程试看结束，后续内容须付费后观看</div>
        <div class="buy-btn">
          <div class="btn-left" @click.stop="goInfo">查看课程介绍</div>
          <div class="btn-right" @click.stop="goPay">付费学习</div>
        </div>
      </div>
    </div>
    <div class="video-placeholder">
      <div class="video-play-holder"></div>
      <div class="pay-tip-holder" v-if="!auth && !adblockNormal"></div>
    </div>

    <!-- 全屏导航 -->
    <div v-show="!smallWindow && goBackShow" class="fullScreen-top">
      <div class="top-title" @click.stop="playerExitFullScreen">
        <div class="goBack icon-back"></div>
        <div class="ml-30">{{ currentVideo.title }}</div>
      </div>
    </div>

    <!-- 全屏广告 -->
    <div class="adfullscreen" v-show="adblockFullscreen">
      <div class="adtitle" @click="exitFullscreen">
        <div class="adBack icon-back mr-4"></div>
        <span v-if="currentVideo">{{ currentVideo.title }}</span>
      </div>
      <div class="adbolck">
        <div class="buy-tip">课程试看结束，后续内容须付费后观看</div>
        <div class="buy-btn">
          <div class="btn-left" @click.stop="goInfo">查看课程介绍</div>
          <div class="btn-right" @click.stop="goPay">付费学习</div>
        </div>
      </div>
    </div>

    <!-- 课程描述 -->
    <div ref="coursetext" class="course-text bg-w">
      <div class="course-title">{{ allData.series_name }}</div>
      <div class="course-msg cl-gruy2 mt-16">
        <div>
          <span class="mr-24">{{ time }}</span
          ><span class="mr-16">视频</span><span class="mr-16">|</span
          ><span>{{ courseList.length + '讲' }}</span>
        </div>
      </div>
      <div class="course-discribe cl-gruy mt-24" v-if="allData.series_desc">
        {{ allData.series_desc }}
      </div>
    </div>

    <div ref="title_placeholder" class="pb-20"></div>
    <!-- 课程目录 -->
    <hxm-sticky :offset-top="titleHeight">
      <div class="video-title bg-w">课程目录</div>
      <div class="video-shadow"></div>
    </hxm-sticky>
    <div class="video-list bg-w" v-if="courseList.length > 0">
      <VideoCard
        :videoData="item"
        :ref="'video' + index"
        :auth="auth"
        :currentIndex="currentIndex"
        v-for="(item, index) in courseList"
        @play="rowClick($event, index)"
        :key="index"
      ></VideoCard>
    </div>
    <div class="bg-w" style="padding-bottom: 1.2rem"></div>
  </div>
</template>

<script>
import VideoCardPlay from '_c/video/VideoCardPlay.vue';
import query from '@/lib/query.js';
export default {
  name: 'Home',
  components: { VideoCard: VideoCardPlay },
  data() {
    return {
      // 权限
      auth: false,
      // 播放时间 由于接口格式改变需要主动获取
      time: '',
      // 播放器对象
      player: null,
      // 标题吸顶位置
      titleHeight: 0,
      showTitle: false,
      config: {
        id: 'play',
      },
      // 外部进入时，有时会指定课程号
      courseId: '',
      // 系列id
      seq: '',
      // 当前课程sid
      sid: '',
      courseList: [],
      // 页面全部数据
      allData: {},
      // 当前播放位置
      currentIndex: '',
      currentVideo: {},
      buyOverlayShow: false,
      // 普通模式广告
      adblockNormal: false,
      // 全屏广告
      adblockFullscreen: false,
      // 小窗口模式
      smallWindow: true,
      goBackShow: true,
      // 安卓5无法播放
      lowVersion: false,
      // 运营落地页地址
      payUrl: '',
      playLog: [],
    };
  },
  created() {
    window.statConf.page(_Global.stat.home);
    window.statConf.click('spbf');
    this.$pageStatus.loading();
    this.getPlayLog();
    this.getVideoVersion();
  },
  mounted() {
    _t.setTitleColor({ white: '#020202', black: '#020202' });
    this.getRouterParam();
    window.callNativeHandler('notifyWebHandleEvent', {
      method: 'WebviewBounce',
      params: {
        // 0：关闭，非0：开启
        bounce: 0,
      },
    });
  },
  beforeDestroy() {
    this.videoPause();
  },
  watch: {
    adblockNormal() {
      this.$nextTick(() => {
        const el = this.$refs.coursetext;
        if (el) {
          // -1避免像素误差
          this.titleHeight = el.offsetTop - 1;
        }
      });
    },
  },
  methods: {
    // 从session取播放记录
    getPlayLog() {
      const userId = window.getUserid();
      // 记录放在本地同步
      if (userId) {
        let playLog = window.localStorage.getItem(`${userId}-wealth_key-course-log`);
        playLog = _t.jsonPase(playLog);
        if (playLog) {
          this.playLog = playLog;
        }
      }
    },
    // 主动，被动暂停时添加记录（主动暂停不触发暂停事件）
    setPlayLog() {
      const userId = window.getUserid();
      if (!userId) {
        return;
      }
      let { currentTime } = this.player;
      currentTime = Math.round(currentTime);
      const startLimit = 10;
      const maxLength = 20;
      // 开始时间短不记录
      if (currentTime < startLimit) {
        return;
      } else if (this.player.ended) {
        // 结束播放时删除记录
        const playIndex = _t.getItemByKey(this.playLog, 'courseId', this.currentVideo.course_id);
        if (playIndex > -1) {
          this.playLog.splice(playIndex, 1);
        }
      } else {
        // 替换，添加记录
        const param = {
          courseId: this.currentVideo.course_id,
          currentTime: this.player.currentTime,
        };
        const playIndex = _t.getItemByKey(this.playLog, 'courseId', this.currentVideo.course_id);
        // 先删后增
        if (playIndex > -1) {
          this.playLog.splice(playIndex, 1);
        }
        this.playLog.push(param);
      }
      if (this.playLog.length > maxLength) {
        this.playLog.splice(0, this.playLog.length - maxLength);
      }
      window.localStorage.setItem(
        `${userId}-wealth_key-course-log`,
        JSON.stringify(this.playLog)
      );
    },
    // 协议播放
    playVideo(url) {
      window.callNativeHandler(
        'startPlugin',
        {
          params: {
            url,
            title: '',
          },
          cname: 'com.hexin.videoplayplugin.VideoPlayerActivityWithNoSD',
          pname: 'com.hexin.videoplayplugin',
          scheme: 'thsvideo',
        },
        function () {
          // do nothing.
        }
      );
    },
    getVideoVersion() {
      const maxVersion = 6;
      // 端外无处理
      if (window.getOS().android && window.getOS().android < maxVersion) {
        this.lowVersion = true;
      }
    },
    // 请求首页数据
    reqListData() {
      const param = {
        // 约定为1
        page_num: '1',
        page_size: '100',
        theme_id: this.seq,
      };
      query
        .getSeqList(param)
        .then(res => {
          if (res.data) {
            this.formatData(res.data);
            this.$nextTick(() => {
              this.getDomMsg();
            });
            this.$pageStatus.close();
          } else {
            // 课程号不存在时，查询data为null
            this.$pageStatus.close();
            this.mixinErrHandler({}, this.goBack);
          }
        })
        .catch(err => {
          this.$pageStatus.close();
          this.mixinErrHandler(err, this.reload);
        });
    },
    formatData(data) {
      const courseList = data?.series_detail?.course_page?.list || [];
      const allData = data?.series_detail || {};
      // 1有权限 0无权限
      this.auth = String(data.auth) === '1';
      if (courseList && courseList.length > 0) {
        const time = courseList[0].info_date;
        if (time) {
          // 时间特殊处理
          const arr = time.split(' ');
          this.time = arr[0];
        }
        for (let i = 0; i < courseList.length; i++) {
          // 记录编号
          courseList[i].videoId = i + 1;
        }
      }
      const ext = _t.jsonPase(allData.series_ext);
      if (ext) {
        this.payUrl = ext?.mobile?.highendLink;
      }
      this.courseList = courseList;
      this.allData = allData;
      // 定位播放位置 传入的视频位置，或者第一个免费的视频
      if (this.courseId) {
        const index = _t.getItemByKey(this.courseList, 'course_id', this.courseId);
        this.currentIndex = index > -1 ? index + 1 : this.getFirstVideo();
      } else {
        this.currentIndex = this.getFirstVideo();
      }
      this.initVideoBuyId(this.currentIndex);
    },
    // 返回第一个能看的视频位置
    getFirstVideo() {
      if (this.auth) {
        return 1;
      } else {
        return _t.getItemByKey(this.courseList, 'free', 0) + 1;
      }
    },
    // 仅视频遮罩会直接进h5页面
    goPay() {
      // 退出前主动暂停
      this.videoPause();
      const url = `${_Global.url.payIndex}?sid=${this.sid}`;
      _t.jumpBy2804(url);
    },
    goInfo() {
      // 目前支付方式相同
      if (this.payUrl) {
        this.videoPause();
        _t.jumpBy2804(this.payUrl);
      } else {
        this.goPay();
      }
    },
    // 重置遮罩
    resetBlock() {
      this.adblockNormal = false;
      this.adblockFullscreen = false;
    },
    goBack() {
      // 退出前主动暂停
      this.videoPause();
      window.statConf.click(`close.${this.allData.series_id}.${this.currentVideo.course_id}.click`);
      window.callNativeHandler('goback', {
        type: window.getPlatform() === 'iphone' ? 'webview' : 'webpage',
      });
    },
    // 主动暂停视频
    videoPause() {
      if (this.player && !this.player.paused) {
        this.setPlayLog();
        this.player.pause();
      }
    },
    rowClick(event, index) {
      if (+this.courseList[index].free === 1 && !this.auth) {
        this.showHxmDialog();
        return;
      }
      this.resetBlock();
      // 低版本直接播放
      if (this.lowVersion) {
        this.playVideo(this.courseList[index].link);
        return;
      }
      // 先暂停后切换
      this.videoPause();
      // 切换埋点,包括关闭埋点
      window.statConf.click(
        `qhkc.${this.allData.series_id}.${this.courseList[index].course_id}.click`
      );
      window.statConf.click(`close.${this.allData.series_id}.${this.currentVideo.course_id}.click`);
      this.initVideoBuyId(index + 1);
      this.setLog(index);
    },
    // 播放记录，百分比
    setLog(index) {
      const userId = window.getUserid();
      if (userId) {
        let log = window.localStorage.getItem(`${userId}-wealth_key-log`);
        log = _t.jsonPase(log);
        if (log && log.length) {
          const logIndex = _t.getItemByKey(log, 'seq', this.seq);
          if (logIndex > -1) {
            log[logIndex] = {
              seq: this.seq,
              index: index + 1,
              courseId: this.courseList[index].course_id,
            };
          } else {
            log.push({
              seq: this.seq,
              index: index + 1,
              courseId: this.courseList[index].course_id,
            });
          }
        } else {
          log = [
            {
              seq: this.seq,
              index: index + 1,
              courseId: this.courseList[index].course_id,
            },
          ];
        }
        window.localStorage.setItem(`${userId}-wealth_key-log`, JSON.stringify(log));
      }
    },
    showHxmDialog() {
      _t.stopBodyScroll(true);
      this.$dialog({
        title: '功能提示',
        content: '后续课程为付费内容，所有用户须付费后观看',
        btns: [
          {
            text: '以后学习',
            callback: () => {
              _t.stopBodyScroll(false);
            },
          },
          {
            text: '付费学习',
            highlight: true,
            callback: () => {
              _t.stopBodyScroll(false);
              this.goInfo();
            },
          },
        ],
      });
    },
    // 进页面后，有些操作需要获取dom元素
    getDomMsg() {
      const el = this.$refs.coursetext;
      // -1避免像素误差
      this.titleHeight = el.offsetTop - 1;
      const title = this.$refs.title_placeholder;
      this.titleOffset = title.offsetTop + title.clientHeight;
      // 超过四个视屏定位
      const maxnum = 4;
      if (this.currentIndex && this.currentIndex > maxnum) {
        setTimeout(() => {
          // 根据序号取dom位置
          const i = this.currentIndex - 1;
          const playel = this.$refs[`video${i}`];
          const height = playel[0].$el.offsetTop;
          // 吸顶标题的高度
          const fixedHeight = document.querySelector('.video-title ').clientHeight;
          window.scrollTo(0, height - fixedHeight - this.titleHeight);
        }, 0);
      } else {
        // 定位到目录
        if (this.showTitle) {
          window.scrollTo(0, this.titleOffset - this.titleHeight);
        }
      }
    },
    initVideoBuyId(courseId) {
      // 初始化重置导航栏
      this.goBackShow = true;
      // 设置当前播放位置
      this.currentIndex = courseId;
      let index = this.currentIndex - 1;
      // 对应接口错误没有免费课的情况
      if (index < 0) {
        index = 0;
      }
      this.currentVideo = this.courseList[index];
      const rate = 0.5;
      const ratea = 0.75;
      const rateb = 1.25;
      const ratemax = 2;
      if (index > -1) {
        const item = this.courseList[index];
        this.config = {
          id: 'play',
          // volume: 0,
          // defaultMuted: true,
          autoplay: true,
          url: item.link,
          height: '4.22rem',
          width: '100%',
          poster: this.allData.cover,
          playbackRate: [rate, ratea, 1, rateb, ratemax],
        };
        const playIndex = _t.getItemByKey(this.playLog, 'courseId', item.course_id);
        if (playIndex > -1) {
          this.config.lastPlayTime = this.playLog[playIndex].currentTime;
        } else {
          // 因为自动播放，首次记录需要主动添加
          this.setLog(index);
        }
      } else {
        this.$toast('课程不存在');
      }
    },
    getRouterParam() {
      const { courseId, showTitle, sid, seq } = this.$route.query;
      this.sid = sid;
      this.seq = seq;
      this.showTitle = showTitle === 'true';
      if (courseId) {
        this.courseId = Number(courseId);
      }
      if (this.seq) {
        this.reqListData();
      } else {
        this.$toast('请从正确的入口进入');
        // 课程号不存在时，控制退出页面
        this.$pageStatus.close();
        this.mixinErrHandler({}, this.goBack);
      }
    },
    // 安卓，取得视频实例
    getPlayerInstance(playerInstance) {
      this.player = playerInstance;
      this.player.on('ended', this.onVideoEnd);
      this.player.on('getRotateFullscreen', this.enterFullscreen);
      this.player.on('exitRotateFullscreen', this.onExitFullscreen);
      this.player.on('controlShow', this.controlShow);
      this.player.on('controlHide', this.controlHide);
      // 统计埋点行为
      this.player.on('play', this.onVideoPlay);
      this.player.on('pause', this.onVideoPause);
    },
    onVideoPlay() {
      window.statConf.click(`start.${this.allData.series_id}.${this.currentVideo.course_id}.click`);
    },
    onVideoPause() {
      this.setPlayLog();
      window.statConf.click(`pause.${this.allData.series_id}.${this.currentVideo.course_id}.click`);
    },
    controlShow() {
      this.goBackShow = true;
    },
    controlHide() {
      this.goBackShow = false;
    },
    playerExitFullScreen() {
      this.player.exitRotateFullscreen();
    },
    exitFullscreen() {
      this.adblockNormal = true;
      this.adblockFullscreen = false;
      this.playerExitFullScreen();
    },
    // 视频进入全屏
    enterFullscreen() {
      window.statConf.click(`qp.${this.allData.series_id}.${this.currentVideo.course_id}.click`);
      this.smallWindow = false;
    },
    onExitFullscreen() {
      this.smallWindow = true;
    },

    isFullScreen() {
      // 只能通过节点判断全屏
      const el = document.querySelector('.xgplayer-skin-hxm.xgplayer-rotate-fullscreen');
      return el ? true : false;
    },
    // 视频结束相关处理
    onVideoEnd() {
      //编号从1 开始，不需要+1
      window.statConf.click(`close.${this.allData.series_id}.${this.currentVideo.course_id}.click`);
      const index = Number(this.currentIndex);
      if (index < this.courseList.length) {
        // 播放完自动取得下一个视频
        this.playNext(index);
      } else {
        if (!this.auth) {
          this.showBuyOverlay();
        }
      }
    },
    playNext(index) {
      const item = this.courseList[index];
      if (+item.free === 0 || this.auth) {
        // 连续播放时，监听不到上个视频的退出全屏事件
        this.smallWindow = true;
        this.initVideoBuyId(index + 1);
      } else {
        // 尝试取得下一个权限视频
        let flag = 0;
        for (let i = index; i < this.courseList.length; i++) {
          if (+this.courseList[i].free === 0) {
            flag = i;
            break;
          }
        }
        // 取不到，则展示付款广告
        if (flag === 0) {
          this.showBuyOverlay();
        } else {
          // 连续播放时，监听不到上个视频的退出全屏事件
          this.smallWindow = true;
          this.initVideoBuyId(flag + 1);
        }
      }
    },
    // 控制遮罩广告
    showBuyOverlay() {
      const fullscreen = this.isFullScreen();
      if (fullscreen) {
        this.adblockFullscreen = true;
      } else {
        this.adblockNormal = true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.hxm-sticky--fixed {
  .video-shadow {
    display: block;
    width: 7.5rem;
    height: 0.2rem;
    background-image: linear-gradient(180deg, rgba(0, 0, 0, 0.02) 0%, rgba(0, 0, 0, 0) 100%);
    [theme-mode='black'] & {
      background-image: linear-gradient(180deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
    }
  }
}
.bg-r {
  background-color: #e93030;
}
.video-shadow {
  display: none;
}
.adfullscreen {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background-color: #000000;
  z-index: 300;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  .adbolck {
    transform: rotate(90deg);
    position: relative;
  }
  .adtitle {
    position: absolute;
    left: 6.5rem;
    top: 0;
    transform: rotate(90deg);
    transform-origin: bottom left;
    display: flex;
    height: 1rem;
    line-height: 1rem;
    color: #ffffff;
    font-size: 0.3rem;
    white-space: nowrap;
  }
}
.adBack {
  width: 0.44rem;
  height: 0.44rem;
  margin-top: 0.28rem;
}
.fullScreen-top {
  position: fixed;
  pointer-events: none;
  width: 100vh;
  height: 1rem;
  transform-origin: bottom left;
  top: -1rem;
  left: 6.5rem;
  transform: rotate(90deg);
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 10%, rgba(0, 0, 0, 0.79) 100%);
  z-index: 300;
  .top-title {
    display: flex;
    height: 1rem;
    line-height: 1rem;
    color: #ffffff;
    font-size: 0.3rem;
    padding-left: 1rem;
    pointer-events: auto;
  }
}
.back-top {
  position: absolute;
  pointer-events: none;
  top: 0;
  left: 0;
  z-index: 300;
  width: 7.5rem;
  height: 1rem;
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 10%, rgba(0, 0, 0, 0.79) 100%);
}
.goBack {
  position: absolute;
  top: 0.3rem;
  left: 0.32rem;
  width: 0.44rem;
  height: 0.44rem;
  pointer-events: auto;
}
.video-container {
  position: fixed;
  top: 0;
  width: 7.5rem;
  z-index: 100;
}
.adbolck {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 4.22rem;
  background-color: #000000;
  z-index: 200;
  display: flex;
  flex-direction: column;
  .buy-tip {
    margin-top: 1.77rem;
    color: #ffffff;
    line-height: 0.34rem;
    text-align: center;
  }
  .buy-btn {
    margin-top: 0.32rem;
    display: flex;
    justify-content: center;
    font-size: 0.24rem;
    line-height: 0.5rem;
    text-align: center;
    .btn-left {
      width: 2.56rem;
      height: 0.5rem;
      border: 1px solid rgba(255, 255, 255, 0.65);
      border-radius: 0.04rem;
      color: rgba(255, 255, 255, 0.65);
      box-sizing: border-box;
    }
    .btn-right {
      border-radius: 0.04rem;
      width: 2.56rem;
      height: 0.5rem;
      background: #e93030;
      color: #ffffff;
      margin-left: 0.32rem;
    }
  }
}
.video-play {
  height: 4.22rem;
  display: block;
  video {
    width: 100%;
  }
  .lowVersion {
    width: 100%;
    height: 4.22rem;
    display: block;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.pay-tip {
  width: 7.5rem;
  height: 1.16rem;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0.24rem 0.32rem;
  align-items: center;
  .pay-tip-btn {
    width: 1.52rem;
    height: 0.5rem;
    font-size: 0.24rem;
    border-radius: 0.04rem;
    text-align: center;
    line-height: 0.5rem;
    color: #ffffff;
    [theme-mode='black']& {
      color: rgba(255, 255, 255, 0.85);
    }
  }
}
.video-placeholder {
  position: relative;
  .video-play-holder {
    width: 100%;
    height: 4.22rem;
  }
  .pay-tip-holder {
    width: 100%;
    height: 1.16rem;
  }
}
.course-text {
  padding: 0.32rem;
  .course-title {
    height: 0.42rem;
    font-size: 0.34rem;
    line-height: 0.42rem;
    font-weight: bold;
  }
  .course-msg {
    line-height: 0.3rem;
    font-size: 0.24rem;
    display: flex;
    justify-content: space-between;
  }
  .course-discribe {
    line-height: 0.3rem;
    font-size: 0.24rem;
    text-align: justify;
    word-break: break-all;
  }
}
.video-title {
  padding: 0.32rem;
  height: 0.42rem;
  line-height: 0.42rem;
  font-size: 0.32rem;
  font-weight: bold;
}
.video-list {
  padding: 0 0.32rem 0.64rem;
}
</style>
